package com.ebocy.hammer.core.db;

import org.apache.log4j.Logger;

import com.ebocy.hammer.core.db.DAOConstants.DBType;
import com.ebocy.hammer.core.db.mongo.MongoConnection;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.util.Config;
import com.ebocy.hammer.core.util.ServerAddress;
import com.mongodb.MongoOptions;
import com.mongodb.ReadPreference;

/**
 * servive for getting dao action 2012-3-23@author yangshaobo
 */
public class DBConnManager {
	protected static Logger logger = EbocyLogManager.getSystemLogger();
	private static DBType type;
	private static IConnection connection;
	private static IConnection logConnection;

	/**
	 * 初始化连接
	 */
	public static void initConn() {
		connect();
		connectLog();
	}

	private static void connect() {
		type = Config.dbType;
		if (type == null) {
			Config.getInstance().init();
			type = Config.dbType;
		}
		switch (type) {
		case MONGODB:
			connection = MongoConnection.getInstance();
			MongoConnection conn = (MongoConnection) connection;

			/** 数据库配置 */
			ServerAddress serverAddr = Config.dbAddress;
			conn.setHost(serverAddr.getIp());
			conn.setPort(serverAddr.getPort());
			if (!Config.dbNeedAuth) {
				conn.setAuth(false);
			} else {
				conn.setUsername(Config.dbUserName);
				conn.setPassword(Config.dbPassword);
			}
			conn.setDatabase(Config.dbName);
			conn.setReadPreference(ReadPreference.SECONDARY);// 设置从服务器可读
			MongoOptions options = new MongoOptions();
			options.connectionsPerHost = Config.dbConnectionNum;	//连接池大小
			conn.setOptions(options);
			/** 数据库连接 */
			boolean isOk = conn.connect();
			if (!isOk) {
				logger.error("database conn is faild!");
				System.exit(0);
			}
			break;
		}
	}

	private static void connectLog() {
		if (!Config.logDBUsed)
			return;
		type = Config.logDBType;
		switch (type) {
		case MONGODB:
			logConnection = MongoConnection.getInstance();
			MongoConnection conn = (MongoConnection) logConnection;
			/** 数据库配置 */
			ServerAddress serverAddr = Config.logDBAddress;
			conn.setHost(serverAddr.getIp());
			conn.setPort(serverAddr.getPort());
			conn.setDatabase(Config.logDBName);
			if (!Config.logDBNeedAuth) {
				conn.setAuth(false);
			} else {
				conn.setUsername(Config.logDBUserName);
				conn.setPassword(Config.logDBPassword);
			}
			conn.setReadPreference(ReadPreference.SECONDARY);// 设置从服务器可读
			MongoOptions options = new MongoOptions();
			options.connectionsPerHost = Config.logDBConnectionNum;
			conn.setOptions(options);
			/** 数据库连接 */
			boolean isOk = conn.connect();
			if (!isOk) {
				logger.error("log database connection is faild!");
				System.exit(0);
			}
			break;
		}
	}

	public static boolean closeConn() {
		return connection.close() && logConnection.close();
	}

}
